package com.lf.web.service.system.role;

import com.lf.data.Cluster;
import com.lf.data.ClusterUtil;
import com.lf.web.service.ResponseCode;
import com.lf.web.service.ResponseInfo;
import com.lf.web.service.ServiceSupport;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class RoleAddService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(RoleAddService.class);
    private RoleDAO roleDAO;

    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    public String execute() {
        String type = form.getString("type");
        if ("save".equals(type)) {
            return save();
        } else {
            List<Cluster> roles = roleDAO.find(null, null, null);
            context.put("parentId", form.getString("parentId"));
            context.put("roles", roles);
            context.put("check", ClusterUtil.getCheck(Role.class));
            return "add";
        }
    }

    private String save() {
        Role role = new Role();
        boolean result = form.getCluster(role);
        LOGGER.debug("添加角色：" + role);
        if (result) {
            ResponseInfo rj = new ResponseInfo();
            String parentid = role.getString(Role.PARENT_ID);
            List parent;
            if (parentid.equals("")) {
                parent = new ArrayList();
                role.remove(Role.PARENT_ID);
            } else {
                Cluster cluster = roleDAO.findById(parentid);
                if (cluster.isEmpty()) {
                    rj.setCode(ResponseCode.EXIST_NOT);
                    out(rj);
                    return NONE;
                }
                parent = cluster.getList(Role.PARENT);
                role.put(Role.PARENT_ID, cluster.get(Role.ID));
            }
            String id = role.setId();
            parent.add(role.get(Role.ID));
            role.put(Role.PARENT, parent);
            role.put(Role.DEEP, parent.size());
            role.put(Role.LIMIT, new HashMap());
            role.put(Role.CREATED, new Date());
            roleDAO.insert(role);
            rj.setCode(ResponseCode.FINISH);
            rj.put("id", id);
            out(rj);
        } else {
            error(404);
            LOGGER.error("非法添加角色：" + role);
        }
        return NONE;
    }

}
